package com.chc.web.role.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chc.utils.CommonResult;
import com.chc.utils.Msg;
import com.chc.web.role.entity.*;
import com.chc.web.role.service.RoleService;
import com.chc.web.role_menu.entity.RoleMenu;
import com.chc.web.role_menu.service.RoleMenuService;
import com.chc.web.user_role.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2021/12/22/16:41
 * @Description:
 */

@RestController
@RequestMapping("/api/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleMenuService roleMenuService;

    //查询角色列表
    @GetMapping("/list")
    public Msg list(RoleParm parm){
        IPage<Role> list = roleService.list(parm);
        return Msg.success("查询成功!",list);
    }

    //新增角色
    @PostMapping
    public Msg addRole(@RequestBody Role role){
        boolean save = roleService.save(role);
        if(save){
            return Msg.success("新增角色成功!");
        }
        return Msg.error("新增角色失败!");
    }

    //编辑角色
    @PutMapping
    public Msg editRole(@RequestBody Role role){
        boolean save = roleService.updateById(role);
        if(save){
            return Msg.success("编辑角色成功!");
        }
        return Msg.error("编辑角色失败!");
    }
    //删除角色
    @DeleteMapping("/{roleId}")
    public Msg deleteRole(@PathVariable("roleId") Long roleId){
        QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(RoleMenu::getRoleId,roleId);
        boolean b = roleMenuService.remove(queryWrapper);
        boolean b1 = roleService.removeById(roleId);
        if(b && b1){
            return Msg.success("删除角色成功!");
        }
        return Msg.error("删除角色失败!");
    }

    //查询分配权限树回显
    @GetMapping("/getAssignTree")
    public Msg getAssignMenuTree(RoleAssignParm roleParm){
        RolePermissionVo assignMenuTree = roleService.getAssignTree(roleParm);
        return Msg.success("查询成功",assignMenuTree);
    }

    //保存权限
    @PostMapping("/saveAssign")
    public Msg saveAssignRole(@RequestBody RolePermissionParm parm){
        roleService.saveAssignRole(parm.getRoleId(),parm.getList());
        return Msg.success("分配权限成功");
    }

    //获取角色列表，不需要传参数
    @GetMapping("/getList")
    public Msg getList(){
        List<Role> list = roleService.list();
        return Msg.success("查询成功",list);
    }
}
